package server

import (
	"fmt"
	"proxy_resource_test/bootstrap/models"
	"proxy_resource_test/dao"
	"proxy_resource_test/utils/logging"
)

// InTaskStatistics 将数据统计到数据库中
func InTaskStatistics(list []models.TaskStatistics) error {
	if len(list) > 0 {
		err := dao.GetSqlDB().Table(models.MakeTaskStatistics.TableName()).CreateInBatches(list, len(list)).Error
		return err
	}
	return nil
}

// GetTaskStatistics 获取统计数据
func GetTaskStatistics(param models.StatisticsParam) (list []models.TaskStatistics, err error) {
	query := dao.GetSqlDB().Table(models.MakeTaskStatistics.TableName())
	if param.StartTime > 0 {
		query = query.Where("created_at >= ? ", param.StartTime)
	}
	if param.EndTime > 0 {
		query = query.Where("created_at <= ? ", param.EndTime)
	}
	err = query.Where("operate = ? ", param.Operate).Limit(1000).Find(&list).Error
	return list, err
}

func AutoMigrateStInfo() {
	var info models.TaskStatistics
	if !dao.GetSqlDB().Migrator().HasTable(info.TableName()) {
		if err := dao.GetSqlDB().Table(info.TableName()).AutoMigrate(&models.TaskStatistics{}); err != nil {
			logging.Error(fmt.Sprintf("AutoMigrateInfo error: %v", err))
		}
	}
}
